package com.example.rwq_test.threadLocal;

import java.util.concurrent.TimeUnit;

/**
 * InheritableThreadLocal可以让子线程获取到父线程ThreadLocal但不能获取同级线程
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2024/4/15
 */
public class InheritableThreadLocalMain {
    private static final ThreadLocal<String> STRING_THREAD_LOCAL = new InheritableThreadLocal();
    private static final ThreadLocal<Integer> INTEGER_THREAD_LOCAL = new InheritableThreadLocal();
    public static void main(String[] args) {
        STRING_THREAD_LOCAL.set("dingdang4D帅得一匹");
        Thread t1 = new Thread() {
            @Override
            public void run() {
                super.run();
                System.out.println("t1 get mian thread value: " + STRING_THREAD_LOCAL.get());
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                super.run();
                INTEGER_THREAD_LOCAL.set(2);
                System.out.println("t2 set integer value: " + INTEGER_THREAD_LOCAL.get());
            }
        };
        t2.start();

        //等t2设置完
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Thread t3 = new Thread() {
            @Override
            public void run() {
                super.run();
                System.out.println("t3 get integer value: " + INTEGER_THREAD_LOCAL.get());;
            }
        };
        t3.start();
    }
}
